package com.k7.mobile.platform.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

public class ObjectUtil {

	public static byte[] objectToBytes(Object obj) {
		byte[] result = null;
		ByteArrayOutputStream byteOutputStream = null;

		Hessian2Output objectOutputStream = null;

		try {
			byteOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new Hessian2Output(byteOutputStream);

			objectOutputStream.startMessage();
			objectOutputStream.writeObject(obj);
			objectOutputStream.completeMessage();
			objectOutputStream.flush();

			result = byteOutputStream.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != objectOutputStream) {
				try {
					objectOutputStream.close();
					byteOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public static <T> T bytesToObject(byte[] bytes) {

		Object result = null;
		ByteArrayInputStream byteInputStream = null;

		Hessian2Input objectInputStream = null;

		try {
			byteInputStream = new ByteArrayInputStream(bytes);
			objectInputStream = new Hessian2Input(byteInputStream);

			objectInputStream.startMessage();
			result = objectInputStream.readObject();
			objectInputStream.completeMessage();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != objectInputStream) {
				try {
					objectInputStream.close();
					byteInputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return (T) result;
	}
}
